using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Controls;
using MindFactorial.LaunchPoint.Common;


namespace MindFactorial.LaunchPoint.Console.Library
{
    /// <summary>
    /// Represents a management object for the top level menu of the console.  This object
    /// can be used to access and add menus to the console menu tree
    /// </summary>
    public class TopLevelMenuManager : ConsoleManager
    {
        Dictionary<string, MenuContextPresenter> _menus = new Dictionary<string, MenuContextPresenter>();
        Menu _mainMenu;

        internal TopLevelMenuManager(Menu mainMenu)
        {
            this._mainMenu = mainMenu;
        }

        /// <summary>
        /// Gets a specific menu context presenter from the top level menu tree
        /// </summary>
        /// <param name="topLevelMenuName"></param>
        /// <returns></returns>
        public MenuContextPresenter this[string topLevelMenuName]
        {
            get
            {

                if (!_menus.ContainsKey(topLevelMenuName))
                {
                    foreach (MenuItem item in _mainMenu.Items)
                    {

                        if (item.Tag.ToString() == topLevelMenuName)
                        {
                            MenuContextPresenter presenter = new MenuContextPresenter(item);
                            _menus.Add(topLevelMenuName, presenter);
                            return presenter;
                        }
                    }
                }
                else
                    return _menus[topLevelMenuName];


                return null;

            }
        }

        /// <summary>
        /// Adds a menu item to the top level list
        /// </summary>
        /// <param name="menuItemName"></param>
        /// <param name="insertionIndex"></param>
        public void Add(string menuItemName, int? insertionIndex)
        {
            MenuItem item = new MenuItem();
            item.Header = menuItemName;
            item.Tag = menuItemName;
            if (insertionIndex.HasValue)
            {
                if (insertionIndex.Value < _mainMenu.Items.Count)
                    _mainMenu.Items.Insert(insertionIndex.Value, item);
                else
                {
                    ApplicationException appex = new ApplicationException("The specified menu insertion index is greater than the number of available items in the menu");
                    Logger.Log("19C0CBED-E817-4189-A081-C3352B4A3409", appex);
                    throw appex;
                }
            }
            else
            {
                _mainMenu.Items.Add(item);
            }
        }
    }
}
